package com.xh.rufongwallpaper.common.utils;

import javax.servlet.http.HttpServletRequest;

/**
 * HTTP请求工具类
 *
 * @author XH
 */
public class RequestUtils {

    /**
     * 获取客户端真实IP
     *
     * @param request HTTP请求
     * @return IP地址
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (isUnknown(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (isUnknown(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (isUnknown(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (isUnknown(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (isUnknown(ip)) {
            ip = request.getRemoteAddr();
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }

    /**
     * 判断IP是否为未知
     *
     * @param ip IP地址
     * @return 是否为未知IP
     */
    private static boolean isUnknown(String ip) {
        return ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip);
    }
    
    /**
     * 私有构造方法，防止实例化
     */
    private RequestUtils() {
        throw new IllegalStateException("Utility class");
    }
} 